package rpcclient

import (
	"fmt"
	"gitee.com/851537/gbase"
	"sync"
)

var (
	//key=addr:serviceName value:*Client
	clients sync.Map
)

// 首次生成时rpcKey必传
// addr fmt:ip:port
func GetClient(addr string, serviceName string, rpcKey ...string) (client *Client) {
	if c, ok := clients.Load(fmt.Sprintf("%s:%s", addr, serviceName)); ok {
		return c.(*Client)
	}
	gbase.PanicRecover(func() {
		var err error
		opts := make([]gbase.Option[*Client], 0)
		opts = append(opts, WithAddr(addr))
		opts = append(opts, WithService(serviceName))
		if len(rpcKey) > 0 {
			opts = append(opts, WithSecKey(rpcKey[0]))
		}
		client, err = NewClient(opts...)
		if err != nil {
			gbase.Panic("生成RPC客户端失败,%s", err.Error())
		}
		clients.Store(serviceName, client)
	})
	return
}
